<?php
namespace backend\controllers;

use backend\modules\base\controllers\BaseController;
use backend\modules\cache\models\CacheData;
use backend\modules\orders\models\Cservice;
use backend\modules\orders\models\Invoice;
use backend\modules\orders\models\OrderInfo;
use backend\modules\rbac\models\AuthItemChild;
use backend\modules\rbac\models\Menu;
use backend\modules\rbac\models\MenuPerm;
use common\models\Wxuser;
use backend\modules\marketing\models\ShareReb;
use frontend\modules\orders\models\CserviceImages;
use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use backend\models\LoginForm;

/**
 * Site controller
 */
class SiteController extends BaseController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['logout', 'index','test','invoice','invoicechange','cservice','cservicechange','setinfo'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
//                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    /**
     * Displays homepage.
     *
     * @return string
     */
    public function actionIndex()
    {
//        $re = Yii::t('log','action-index');print_r($re);exit;
        /** @var \callmez\wechat\sdk\Wechat $wechat $wechat */
//        $wechat =Yii::$app->wechat;
////        $urlget = "https://api.weixin.qq.com/cgi-bin/customservice/getkflist?access_token=".$wechat->getAccessToken();
////        $re = $wechat->httpGet($urlget);print_r($re);exit;
//        $url = "https://api.weixin.qq.com/customservice/kfsession/create?access_token=".$wechat->getAccessToken();
//        $arr = ["kf_account" =>"kf2002@Ai_Xiaopu",
//       "openid" =>"oEqJ_s7pLCea38cw50uAnUdYPWQY"];
//        $re = $wechat->httpRaw($url,$arr);print_r($re);exit;
//
//        $wechat->sendText('oEqJ_sxGJ_a-lQJPiH19Ctx96i0c','你好请问有什么需要服务的吗？');
        $newChildARR = array();
        $menuperm = new MenuPerm;
        $roles = $menuperm->getRoleByUser(Yii::$app->user->id);
        foreach($roles as $k=>$v) {
            $childARR = AuthItemChild::find()->select(['child'])->where(['parent'=>$k])->asArray()->all();
            foreach($childARR as $k=>$v) {
                if(substr($v['child'],0,5)=='Index'){
                    $newChildARR[] = $v['child'];
                }
            }
        }

        if(in_array('Index@发票提醒功能',$newChildARR)) {
            $invoice = Invoice::find()
                ->select('i.*,u.wx_name,u.wx_images,oi.pay_time')
                ->from('invoice AS i')
                ->leftJoin('order_info AS oi', 'oi.order_id = i.order_id')
                ->leftJoin('user AS u', 'u.id = oi.user_id')
                ->where(['i.is_payed' => 1, 'hav_buil' => 0])
                ->orderBy(['oi.add_time' => SORT_ASC])
                ->asArray()
                ->all();
        } else{
            $invoice = [];
        }

        if(in_array('Index@售后单',$newChildARR)) {
            $cservice = Cservice::find()
                ->select('c.*,g.goods_name,g.goods_image,oi.order_sn,u.wx_name,u.wx_images')
                ->from('cservice AS c')
                ->leftJoin('order_goods AS og', 'og.rec_id = c.order_goods_id')
                ->leftJoin('order_info AS oi', 'oi.order_id = og.order_id')
                ->leftJoin('goods AS g', 'g.goods_id = og.goods_id')
                ->leftJoin('user AS u', 'u.id = og.user_id')
                ->where(['<>', 'c.is_deal', 3])
                ->andwhere(['<>', 'c.is_deal', -1])
                ->orderBy(['c.created_at' => SORT_ASC])
                ->asArray()
                ->all();
        } else{
            $cservice = [];
        }

        if(in_array('Index@待发货订单',$newChildARR)) {
            $orderUnshipping = OrderInfo::find()
                ->select('oi.*,u.wx_name,u.wx_images')
                ->from('order_info AS oi')
                ->leftJoin('user AS u', 'u.id = oi.user_id')
                ->orderBy(['oi.pay_time' => SORT_ASC])
                ->where(['order_status' => 1])
                ->asArray()
                ->all();
        }else{
            $orderUnshipping = [];
        }

        if(in_array('Index@售后单',$newChildARR)) {
            $orderWarm = OrderInfo::find()
                ->select('oi.*,u.wx_name,u.wx_images')
                ->from('order_info AS oi')
                ->leftJoin('user AS u', 'u.id = oi.user_id')
                ->orderBy(['oi.pay_time' => SORT_ASC])
                ->where(['is_warm' => 1, 'shipping_status' => 0])
                ->asArray()
                ->all();
        } else{
            $orderWarm = [];
        }

        if(in_array('Index@付款提醒',$newChildARR)) {
            $shareRebARR = ShareReb::find()
                ->select('sru.* ,u.wx_name,u.wx_images,sr.is_payed')
                ->from('share_reb AS sr')
                ->leftJoin('user AS u','sr.user_id = u.id')
                ->leftJoin('share_reb_user AS sru','sru.user_id = u.id')
                ->where(['sr.is_payed'=>0])
                ->distinct(['sr.user_id'])
                ->asArray()
                ->All();
        } else{
            $shareRebARR = [];
        }




            $userCount0 = Wxuser::find()->where(['is_gz' => '0'])->count();
            $userCount1 = Wxuser::find()->where(['is_gz' => '1'])->count();
            $userCount2 = Wxuser::find()->where(['is_gz' => '2'])->count();

        return $this->render('index',[
            'cservice'=>$cservice,'orderUnshipping'=>$orderUnshipping,'orderWarm'=>$orderWarm,'invoice'=>$invoice,'shareRebARR'=>$shareRebARR,
            'userCount0'=>$userCount0,
            'userCount1'=>$userCount1,
            'userCount2'=>$userCount2,
            'newChildARR'=>$newChildARR
        ]);
    }

    /**
     *
     */
    public function actionSetinfo()
    {
        $wxUserARR = Wxuser::findAll(['is_gz'=>2]);
        foreach($wxUserARR  as $k=>$v) {
            /** @var \callmez\wechat\sdk\Wechat $wechat $wechat */
            $wechat = Yii::$app->wechat;
            $menberInfo = $wechat->getMemberInfo($v->openid);
            $v->wx_name = $menberInfo['nickname'];
            $v->wx_images = $menberInfo['headimgurl'];
            $v->is_gz = 1;
            if(!$v->save()){

            }
        }
        return $this->redirect('index');
    }

    /**
     * @return string
     */
    public function actionCservice()
    {
        $post = Yii::$app->request->post();
        $cservice_id =$post['cservice_id'];
        $cserviceARR = Cservice::find()->where(['cservice_id'=>$cservice_id])->asArray()->one();
        $cserviceImagesARR = CserviceImages::find()->where(['cservice_id'=>$cservice_id])->asArray()->all();
        return json_encode([true,'cservice'=>$cserviceARR,'cservice_images'=>$cserviceImagesARR]);
    }

    /**
     * @return string
     */
    public function actionCservicechange()
    {
        $post = Yii::$app->request->post();
        $cservice_id =$post['cservice_id'];
        $num =$post['num'];
        $cservice = Cservice::findOne($cservice_id);
        $cservice->is_deal = $num;
        if($cservice->save()) {
            return $this->redirect('index');
        }
    }

    /**
     * @return string
     */
    public function actionInvoice()
    {
        $post = Yii::$app->request->post();
        $invioce_id =$post['invoice_id'];
        $invioceARR = Invoice::find()->where(['invoice_id'=>$invioce_id])->asArray()->one();
        return json_encode([true,'invoice'=>$invioceARR]);
    }

    /**
     * @return string
     */
    public function actionInvoicechange()
    {
        $post = Yii::$app->request->post();
        $invoice_id =$post['invoice_id'];
        $invoice = Invoice::findOne($invoice_id);
        if($invoice->hav_buil==0) {
            $invoice->hav_buil = 1;
        }else{
            $invoice->hav_buil = 0;
        }
        if($invoice->save()) {
            return $this->redirect('index');
        }
    }

    /**
     * Login action.
     *
     * @return string
     */
    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        $cache = new CacheData();
        $cache->del_leftMenu();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        } else {
            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Logout action.
     *
     * @return string
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }
}
